<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogAddOrEdit.visible"
    :width="screenWidth"
    :fullscreen="mobile === 'mobile'"
    :title="dialogAddOrEdit.title"
    draggable
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 15vh"
    @close="closeDialog(false)"
  >
    <el-form
      ref="addOrEditFormRef"
      v-loading="loading"
      :model="formData"
      :rules="rules"
      label-width="170"
      size=""
      style="padding-right: 10px; overflow: auto"
    >
      <el-row justify="start" style="margin-top: 10px">
        <el-col :span="itemSpan">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="projectInfo.name" disabled placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="项目编号" prop="prjNum">
            <el-input v-model="projectInfo.prjNum" disabled placeholder="自动生成" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="项目负责人" prop="name">
            <el-input v-model="projectInfo.linkMan" disabled placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>
        <el-col :span="itemSpan">
          <el-form-item label="负责人联系电话" prop="name">
            <el-input v-model="projectInfo.linkPhone" disabled placeholder="请输入项目名称" />
          </el-form-item>
        </el-col>

        <!--- 计划停工日期的选择范围最小为明天 -->
        <el-col v-if="dialogAddOrEdit.type == 1" :span="itemSpan">
          <el-form-item label="计划停工日期" prop="planStartDate">
            <el-date-picker
              v-model="formData.planStartDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledStartDate"
              placeholder="选择日期"
              @change="changePlanStartDate"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="dialogAddOrEdit.type == 1" :span="itemSpan">
          <el-form-item label="计划复工日期" prop="planEndDate">
            <el-date-picker
              v-model="formData.planEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled-date="disabledEndDate"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>

        <el-col :span="22">
          <el-form-item label="申请理由" prop="reason">
            <el-input
              v-model="formData.reason"
              type="textarea"
              style="width: 100%"
              :row="3"
              placeholder="请输入申请理由"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2"> </el-col>
        <el-col :span="24">
          <el-form-item label="上传证明材料" prop="attachments">
            <el-upload
              v-model:file-list="fileList"
              :action="actionUrl"
              multiple
              :limit="5"
              accept=".doc,.docx,.pdf,.jpg,.png,.xls,.xlsx"
              :on-exceed="handleUploadExceed"
              :on-success="handleUploadSuccess"
              :on-preview="handleUploadPreview"
            >
              <el-button plain size="small">上传附件</el-button>
              <DownloadTemplate :type="templateType"></DownloadTemplate>
              <template #tip>
                <div class="el-upload__tip">仅支持上传doc,docx,xls,xlsx,pdf,jpg,png且不大于5M的文件</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div class="dialog_footer">
        <el-button type="primary" :loading="loading" @click="handleSubmit">{{ dialogAddOrEdit.footBtn }}</el-button>
        <el-button @click="closeDialog(false)">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { AddProjectLockOut } from "@/api/project/workapply/index";
import { ProjectLockOutEditForm, AttachmentsForm } from "@/api/project/workapply/types";
import { useScreen } from "@/store/modules/screen";
import { FormRules } from "element-plus/es/components/form/src/types";
import DownloadTemplate from "@/views/common/DownloadTemplate/index.vue";
import type { UploadUserFile } from "element-plus";
import moment from "moment";

//声明变量
const actionUrl = ref(`${import.meta.env.VITE_APP_BASE_API}/api/v1/common/upload`);

const projectInfo = JSON.parse(localStorage.getItem("project") ?? "{}");

//上传文件列表
const fileList = ref<UploadUserFile[]>([]);

const screenStore = useScreen();
const mobile = computed(() => screenStore.device);
const screenWidth = ref(900);
const itemSpan = ref(12);
const props = defineProps({
  dialogAddOrEdit: {
    type: Object,
    default: () => ({
      visible: false,
      title: "新增",
      footBtn: "确认新增",
      id: 0,
      type: 1, //1为停工 2 为复工
    }),
  },
});
const templateType = ref(105);
const { dialogAddOrEdit } = toRefs(props);
const emit = defineEmits(["sendClose"]);
const loading = ref(false);

const formData = reactive<ProjectLockOutEditForm>({
  attachments: [],
  reason: "",
  status: 0,
});
const addOrEditFormRef = ref(ElForm);

const rules = reactive<FormRules<ProjectLockOutEditForm>>({
  reason: [{ required: true, message: "申请理由不能为空", trigger: "blur" }],
  planStartDate: [{ required: true, message: "计划停工日期不能为空", trigger: "blur" }],
  planEndDate: [{ required: true, message: "计划复工日期不能为空", trigger: "blur" }],
});

const disabledStartDate = (time: Date) => {
  return time.getTime() <= new Date(moment().add(-1, "days").format("YYYY-MM-DD")).getTime();
};
const disabledEndDate = (time: Date) => {
  if (formData.planStartDate) {
    return time.getTime() <= new Date(formData.planStartDate).getTime();
  }
  return time.getTime() > new Date(moment().format("YYYY-MM-DD")).getTime();
};
const changePlanStartDate = () => {
  formData.planEndDate = null;
};

/* 附件上传 */
const handleUploadPreview = (file: any) => {
  ElMessage.info(file.url);
};
const handleUploadExceed = () => {
  ElMessage.error("最多上传5个附件");
};
const handleUploadSuccess = (response: any) => {
  if (response.type === 0) {
    if (response.success) {
    } else {
      ElMessage.error(response.msg);
    }
  } else {
    ElMessage.error(response.msg);
  }
};

onMounted(() => {
  initScreen();
  if (dialogAddOrEdit.value.type == 1) {
    templateType.value = 105;
  }
  if (dialogAddOrEdit.value.type == 2) {
    templateType.value = 102;
  }
});

function initScreen() {
  if (mobile.value === "mobile") {
    screenWidth.value = screenStore.screenWidth;
    itemSpan.value = 24;
  } else {
    screenWidth.value = 900;
    itemSpan.value = 12;
  }
}

/**
 * 关闭弹窗
 */
function closeDialog(needRefresh: boolean) {
  emit("sendClose", needRefresh);
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  fileList.value = [];
  addOrEditFormRef.value.resetFields();
  addOrEditFormRef.value.clearValidate();
}

/**
 * 项目表单提交
 */
function handleSubmit() {
  addOrEditFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (fileList.value.length > 0) {
        let attachments = [] as AttachmentsForm[];
        fileList.value.forEach((item: any) => {
          if (item.status === "success") {
            if (item.response) {
              attachments.push({
                attachmentId: item.response.data,
              });
            }
          }
        });
        formData.attachments = attachments;
      }
      formData.status = dialogAddOrEdit.value.type;
      AddProjectLockOut(formData)
        .then((resp) => {
          if (resp.type === 0) {
            if (resp.success === true) {
              ElMessage.success(resp.msg);
              closeDialog(true);
            } else {
              ElMessage.warning(resp.msg);
            }
          } else {
            ElMessage.warning(resp.msg);
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}
</script>

<style lang="scss" scoped>
:deep(.el-form-item) {
  flex-wrap: wrap;
}

:deep(.el-input) {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}
:deep(.el-cascader) {
  width: 100%;
}
:deep(.el-input__wrapper) {
  width: 100%;
}

:deep(.el-form-item__label) {
  color: #696868;
  font-size: 13px;
}
:deep(.el-upload__tip) {
  display: inline-block;
  margin-left: 10px;
}
</style>
